var React = require('react');

var Container = require('amazeui-touch').Container,
    List = require('amazeui-touch').List,
    Group = require('amazeui-touch').Group,
    Badge = require('amazeui-touch').Badge;

var $ = require('jquery');

import Mask from "../common/Mask";
import Alert from "../common/Alert";

import MessageContent from './MessageContent';


const MessageCenter = React.createClass({
    messageCenterUrl: 'ajax/messageCenter.json',
    getDefaultProps() {
        return {
            headerTitle: '消息中心',
            withFooter: true
        };
    },
    loadRelationship() {
        this.refs.mask.openMask();
        var t = this;
        $.ajax({
            type: "GET",
            url: this.messageCenterUrl,
            success: function (res) {
                t.refs.mask.closeMask();
                if (res.state == 0) {
                    t.setState({
                        messageList: res.data
                    });
                } else {
                    t.refs.alert.openModal(res.message);
                }
            },
            error: function (res, error) {
                t.refs.mask.closeMask();
                console.error(res);
                console.error(error);
            },
            dataType: 'json'
        });
    },
    getInitialState() {
        return {
            messageList: []
        };
    },
    componentDidMount(){
        this.loadRelationship();
    },
    getImg(imgUrl){
        return <img width="48" src={imgUrl}/>;
    },
    splitString(msg, length = 10){
        var message = msg.substring(0, length)
        if (message.length < msg.length) {
            message = message + "...";
        }
        return message;
    },
    getUnreadIcon(num){
        return <Badge rounded amStyle="alert">{num}</Badge>
    },
    render() {
        return (
            <Container {...this.props} ref="form" className="container-fill container-scrollable">
                <Mask ref="mask"/>
                <Alert ref="alert"/>
                <Group>
                    <List>
                        {this.state.messageList.map((message, i) => {
                            return (
                                <List.Item
                                    key={i}
                                    title={message.name}
                                    media={this.getImg(message.avatar)}
                                    subTitle={this.splitString(message.desc, 10)}
                                    after={this.getUnreadIcon(message.unreadCnt)}
                                    href={"/#/messagecontent/" + message.id}
                                />
                            );
                        })}
                    </List>
                </Group>
            </Container>

        );
    }
});

export default MessageCenter;
